<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/21
 * Time: 上午11:44
 */

namespace App\Http\Services;

use App\Events\RoomRegisterEvent;
use App\Exceptions\ErrorCodeException;
use App\Http\Model\ContentCheck;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\FinanceRoomWallet;
use App\Http\Model\FinanceWealth;
use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\Medal;
use App\Http\Model\Musics;
use App\Http\Model\OutJson;
use App\Http\Model\Prop;
use App\Http\Model\Room;
use App\Http\Model\RoomBackgroundPicture\BackgroundPictureManagement;
use App\Http\Model\RoomDynamicLog;
use App\Http\Model\RoomHeart;
use App\Http\Model\RoomHostMicro;
use App\Http\Model\RoomHot;
use App\Http\Model\RoomMelee;
use App\Http\Model\RoomMicro;
use App\Http\Model\RoomMusic;
use App\Http\Model\RoomScore;
use App\Http\Model\RoomTally;
use App\Http\Model\RoomUser;
use App\Http\Model\RoomWaitbit;
use App\Http\Model\RoomRecommendLabel;
use App\Http\Model\SystemConfig;
use App\Http\Model\Union;
use App\Http\Model\User;
use App\Http\Model\Hint;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\UserProp;
use App\Http\Model\UserRegisterLog;
use App\Lib\agora;
use App\Lib\Publisher;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Http\Model\RoomTurntable;
use App\Http\Model\RoomVoiceCheck;
use App\Http\Model\Mall;
use Exception;
use Illuminate\Support\Facades\Log;
use App\Http\Services\UserServices;
use App\Http\Services\RoomMsgServices;
use App\Modules\LuckDraw\Models\UserPropModel;
use Illuminate\Support\Facades\Redis;
use App\Http\Services\ThinkingdataServices;
use App\Http\Services\NewRoomServices;
use App\Http\Services\MsgServices;

class RoomServices extends CommonServices
{
    private $model_room;
    private $model_user;
    private $model_room_dynamic_log;
    private $model_room_user;
    private $model_userwallet;
    private $model_financewealth;
    private $model_room_hostmicro;
    private $model_room_micro;
    private $model_room_waitbit;
    private $model_finance_room_wealth;
    private $model_finance_room_wallet;
    protected $model_room_music;
    private $model_room_hot;
    private $modelRoomHeart;
    private $modelRoomTally;
    private $modelRoomMelee;
    private $modelRoomTurntable;
    private $modelUnion;
    private $userPropModel;
    private $roomRecommendLabel;

    private $contentCheckModel;
    protected $modelMusic;
    protected $medalModel;
    protected $propModel;
    protected $mallGoods;
    protected $finance_recharge_order_model;//充值记录表
    protected $luck_draw_user_prop_model;//许愿池表
    
    protected $firstRecharge_key = "USER:FIRSTRECHARGE:";//string USER:FIRSTRECHARGE:{userid} => {int}  新用户首次弹窗记录
    protected $crossRoomPkRedisList = 'CROSS:ROOM:PK:ALLIST'; //所有玩PK的房间列表 set CROSS:ROOM:PK:ALLIST=>roomID
    
    private $service_user;
    private $room_msg_services;
    protected $tdService;
    protected $newRoomServices;
    protected $zegoService;
    protected $msgService;


    public function __construct()
    {
        $this->model_room = new Room();
        $this->model_room_dynamic_log = new RoomDynamicLog();
        $this->model_user = new User();
        $this->model_room_user = new RoomUser();
        $this->model_userwallet = new FinanceUserWallet();
        $this->model_financewealth = new FinanceWealth();
        $this->model_room_hostmicro = new RoomHostMicro();
        $this->model_room_micro = new RoomMicro();
        $this->model_room_waitbit = new RoomWaitbit();
        $this->model_finance_room_wealth = new FinanceRoomWealth();
        $this->model_finance_room_wallet = new FinanceRoomWallet();
        $this->model_room_music = new RoomMusic();
        $this->model_room_hot = new RoomHot();
        $this->modelRoomHeart = new RoomHeart();
        $this->modelRoomTally = new RoomTally();
        $this->roomRecommendLabel = new RoomRecommendLabel();
        $this->modelRoomMelee = new RoomMelee();
        $this->modelRoomTurntable = new RoomTurntable();
        $this->modelUnion = new Union();
        $this->userPropModel = new UserProp();
        $this->contentCheckModel = new ContentCheck();
        $this->modelMusic = new Musics();
        $this->medalModel = new Medal();
        $this->propModel = new Prop();
        $this->mallGoods = new Mall;
        $this->service_user = new UserServices();
        $this->room_msg_services = new RoomMsgServices();
        $this->finance_recharge_order_model = new FinanceRechargeOrder(); //充值记录表
        $this->luck_draw_user_prop_model = new UserPropModel();//许愿池抽奖券
        $this->tdService = new ThinkingdataServices();
        $this->newRoomServices = new NewRoomServices();
        $this->zegoService = new ZegoServices();
        $this->msgService = new MsgServices();

    }

    /**
     * 获取房间信息
     * @param $room_id
     * @return int
     */
    public function info($room_id)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return null;
        }
        $room_item = $this->model_room->get_room($room_id);
        if (empty($room_item)) {
            return Hint::ROOM_NO_EXIST; //房间不存在
        }
        $user_id = $current_user['user_id'];

        $close_timestamp = $this->model_room->get_close_timestamp($room_id);
        $opened = $this->model_room->get_opened($room_id);
        $room_item['opened'] = $opened;
        $room_item['allow_open'] = null;
        $role = null;
        if (!$opened) {
            $room_item['allow_open'] = false;
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
            if ($role == 0) {
                return Hint::ROOM_NOT_OPEN;
            } else {
                $room_item['allow_open'] = true;
            }
        }

        if ($this->model_room->get_shotoff($room_id, $user_id)) {
            return Hint::ROOM_USER_SHOT_OFF;
        }


        if ($role === null) {
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        }


        $pwd = 0;
        $room_password = $this->model_room->get_password($room_id);
        if ($room_password !== null) {
            $pwd = 1;
        }

        $host_user = $this->model_user->get_user($room_item['user_id']);
        $room_item['host'] = $host_user;
        $room_item['wealth_value'] = $this->model_finance_room_wallet->get_wallet($room_id);

        $users_count = $this->model_room_user->get_users_count($room_id);
        $room_item['online_count'] = $users_count;
        $room_item['is_block'] = $this->model_room->get_block($room_id, $user_id);
        $room_item['is_collect'] = $this->model_room->get_collect($room_id, $user_id);
        $room_item['user_role'] = $role;
        $room_item['close_timestamp'] = $close_timestamp;
        $room_item['chat_room_id'] = intval(config('rong_cloud.room_id_offset')) + intval($room_item['room_id']);
        //$room_item['attires'] = $this->model_mall->getGoodsAttire($user_id);
        $room_item['password'] = $pwd;
        $room_item['free_micro'] = $this->model_room->get_freemicro($room_id);
        $room_item['screen_opened'] = $this->model_room->get_screen_opened($room_id);
        $room_item['volume_closed'] = $this->model_room->get_volume_closed($room_id);
        $room_item['mode_type'] = $this->model_room->getModeType($room_id);
        $room_item['topic'] = $this->model_room->getTopic($room_id);
        $room_item['melee_opened'] = $this->modelRoomMelee->getState($room_id);
        $room_item['tally_opened'] = $this->modelRoomTally->opened($room_id);
        $room_item['heart_opened'] = $this->modelRoomHeart->getState($room_id);
        if ($room_item['heart_opened'] > 0) {
            $room_item['heart_opened'] = 1;
        }
        $room_item['turntable_opened'] = $this->modelRoomTurntable->getTurntableOpened($room_id);
        $parse_app_UA = $this->parse_app_UA();

        $room_item['pk_opened'] = 0; //获取是否开启PK
        //获取房间公会信息
        $union_room = $this->modelUnion->checkUnionRoom($room_id);
        $room_item['has_union'] = 0; //是否有公会
        $room_item['union_id'] = 0; //公会ID
        if ($union_room) {
            $room_item['has_union'] = 1;
            $room_item['union_id'] = $union_room['un_id'];
        }

        //检查房间背景图是否可用
        if (!empty($room_item['background_pic'])) {
            $exceed = BackgroundPictureManagement::checkPictureExpire($room_item['background_pic']);
            if ($exceed == false) {
                $room_item['background_pic'] = "";
            }
        }

        $room_item['hot'] = $this->model_room_hot->get($room_id);

        // 获取神豪开关状态
        $room_item['god_hao_switch'] = $this->model_room->getGodHaoSwitch($room_id);

        $room_item['gift_show_switch'] = (new RoomServices())->getRoomSwitchCommon($room_id, 'gift_show_switch');

        return $room_item;
    }


    /**
     * 开启房间方法
     * @param $room_id
     * @param $name
     * @param $notice
     * @param $image
     * @param $desc
     * @return int
     */
    public function open($room_id, $name, $notice, $image, $desc, $type_id, $free_micro, $modeType = 0, $room_tag_id, &$firstOpenFlag = false, &$setNameSuccess, $room_mode=0, $game_area = "", $game_level = "", string $background_pic = "",$admin_id)
    {
        $opened = $this->model_room->get_opened($room_id);
        if ($opened) {
            return Hint::ROOM_IS_OPEN;
        }
        if(!empty($admin_id)){
            $current_user['user_id']=$admin_id;
        }else{
            $current_user = $this->model_user->get_current_user();
            if (empty($current_user)) {
                return Hint::LOGIN_OUT;
            }
            $role = $this->model_room->get_role($room_id, $current_user['user_id']);
            if ($role === 0) {
                return Hint::AUTH_ERROR;
            }

            //判断用户是否完成实名认证
            if ($current_user['active_certify'] != 1) {
                return Hint::USER_NOT_CERTIFICATION;
            }

            // 查询房间信息 类型是否是 0=普通房间 默认为首次打开
            $roomData = $this->model_room->get_room($room_id);

            if ($roomData['business_type'] == 1 && $roomData['certified'] == 0) {
                return Hint::ROOM_NOT_CERTIFIED;
            }

        }


        //记录房间开启日志
        $roomOpenId = $this->model_room->insertRoomOpenLog($room_id, $current_user['user_id']);
        if(empty($roomOpenId)) {
            return Hint::ERR_SYS_FAIL;
        }

        $parse_app_UA = $this->parse_app_UA();//陪伴小屋

        // 设置Aig声网房间
        $this->model_room->setAig($room_id);
        $this->model_room->set_opened($room_id);
        if (empty($roomData['room_type']['id'])) {
            // 首次开房 发送动态消息标识
            $firstOpenFlag = true;
        } else {
            $firstOpenFlag = false;
        }

        //新增房间区服变更
        if ($game_area !== null) {
            $this->model_room->setRoomGameArea($room_id, $game_area);
        }
        //新增房间段位变更
        if ($game_level !== null) {
            $this->model_room->setRoomGameLevel($room_id, $game_level);
        }

        //新增房间段位变更
        $this->model_room->setRoomGameLevel($room_id, $game_level);
        //房间模式变更
        $room_mode = empty($room_mode) ? 1 : $room_mode;
        $this->model_room->setRoomMode($room_id, $room_mode);
        $this->room_msg_services->roomModeMsg($room_id, $room_mode);

        if ($roomData['business_type'] == 0 && $type_id !== null) {
            $ret_type = $this->set_room_type($room_id, $type_id);
            $this->model_room->set_room_type($room_id, $type_id);
            if ($ret_type != Hint::SUCCESS) {
                return $ret_type;
            }
        }

        $this->model_room_hot->del($room_id);

        //节日不允许修改的时间范围
        list($forbiddenStart, $forbiddenEnd) = SystemConfigServices::getForbiddenTimeForUpdate();
        // 默认设置房间名称成功标识
        $setNameSuccess = true;
        if ($name !== null) {
            //国庆期间不允许修改房间标题
            if(time()< $forbiddenStart || time() > $forbiddenEnd){
                $setName = $this->model_room->set_name($room_id, $name);
                if ($setName === 'SET_NAME_FALSE') {
                    $setNameSuccess = false;
                }
            }

        }

        if ($notice !== null) {
            $this->model_room->set_notice($room_id, $notice);
        }

        // 默认允许小屋设置封面  and $roomData['business_type'] == 0
        if ($image !== null) {
            //国庆期间不允许修改头像
            if(time()< $forbiddenStart || time() > $forbiddenEnd){
                $this->model_room->set_image($room_id, $image);
            }

        }

        if ($desc !== null) {
            $this->model_room->set_desc($room_id, $desc);
        }
        if ($free_micro !== null) {
            $this->model_room->set_freemicro($room_id, $free_micro);
        } else {
            $this->model_room->set_freemicro($room_id, 1);
        }

        if ($modeType == 0){
            $modeType = 1;
        }
        $this->model_room->setModeType($room_id, $modeType);

        // 设置房间标签
        if (!empty($room_tag_id)) {
            $this->model_room->setRoomTagId($room_id, $room_tag_id);
        }

        //重新打开房间后删除已有的音乐权限
        $this->modelMusic->delMusicPermission($room_id);

        if ($background_pic !== '') {
            $this->model_room->set_background_pic($room_id, $background_pic);
        }

        // 每次开启房间重置神豪开关
        $this->model_room->setGodHaoSwitch($room_id, 0);

        //设置已开启房间信息
        $this->model_room->setRoomOpenListCache($room_id, 'roomId', $room_id);
        $this->model_room->setRoomOpenListCache($room_id, 'roomMode', $room_mode);
        $this->model_room->setRoomOpenListCache($room_id, 'roomUserNum', 0);
        $this->model_room->setRoomOpenListCache($room_id, 'gameId', 0);
        $this->model_room->setRoomOpenListCache($room_id, 'pkId', 0);
        $this->model_room->setRoomOpenListCache($room_id, 'pkEndTime', 0);
        $this->model_room->setRoomOpenListCache($room_id, 'roomOpenId', $roomOpenId);

        //设置房间热度
        $this->newRoomServices->updateRoomStartHotNum($room_id, $roomOpenId);
        $this->newRoomServices->updateRoomHotNum($roomOpenId);

        $this->model_room->get_room($room_id);

        //埋点
        $this->tdService->handleTrack('open_room', ['user_id'=>$current_user['user_id'], 'roomOpenId'=>$roomOpenId]);

        return Hint::SUCCESS;
    }

    /**
     * 设置房间基础参数
     * @param $room_id
     * @param $name
     * @param $notice
     * @param $image
     * @param $desc
     * @return int
     */
    public function edit($room_id, $name, $notice, $image, $desc, $room_tag_id, $room_mode, $game_area = "", $game_level = "", $type_id = null)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        if ($role === 0) {
            return Hint::AUTH_ERROR;
        }
        if ($name != null) {
            $setName = $this->model_room->set_name($room_id, $name);
            if ($setName === 'SET_NAME_FALSE') {
                return $setName;
            }
        }
        if ($notice != null) {
            $this->model_room->set_notice($room_id, $notice);
        }
        if ($image != null) {
            $this->model_room->set_image($room_id, $image);
        }
        if ($desc != null) {
            $this->model_room->set_desc($room_id, $desc);
        }

        // 设置房间标签
        if (!empty($room_tag_id)) {
            $this->model_room->setRoomTagId($room_id, $room_tag_id);
        }

        //新增房间区服变更
        if (!empty($game_area)) {
            $this->model_room->setRoomGameArea($room_id, $game_area);
        }
        //新增房间段位变更
        if (!empty($game_level)) {
            $this->model_room->setRoomGameLevel($room_id, $game_level);
        }
        //房间模式变更
        if (!empty($room_mode)) {
            $this->model_room->setRoomMode($room_id, $room_mode);
            $this->room_msg_services->roomModeMsg($room_id, $room_mode);
            //设置已开启房间信息
            $this->model_room->setRoomOpenListCache($room_id, 'roomMode', $room_mode);
        }

        // 查询房间信息 类型是否是 0=普通房间 默认为首次打开
        $roomData = $this->model_room->get_room($room_id);
        if ($roomData['business_type'] == 0 && $type_id !== null) {
            //切换房间类型成功之后再设置房间类型
            $ret_type = $this->set_room_type($room_id, $type_id);
            if ($ret_type != Hint::SUCCESS) {
                return $ret_type;
            }
        }
    }


    /**
     * 获取权限管理员列表
     * @param $room_id
     * @param $page_index
     * @param $page_size
     * @return array|int
     */
    public function get_roles($room_id, $page_index, $page_size)
    {

        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $user_id = $current_user['user_id'];

        $role = $this->model_room->get_role($room_id, $user_id);
        if ($role != 2) {
            return Hint::AUTH_ERROR;
        }

        $roles_count = $this->model_room->get_roles_count($room_id);
        $roles_limit = $this->model_room->get_roles_limit($room_id, $page_index * $page_size, $page_size);
        $rolesArr = array_column($roles_limit, null, 'user_id');

        //有效邀请管理员列表
        $invite_users = $this->model_room->get_admin_valid_invite($room_id);
        $online_invite_user_ids = [];
        foreach ($invite_users as $u){
            if($room_id == $this->model_room_user->get_user_cur_room($user_id)){
                $online_invite_user_ids[] = $u['invite_user_id'];
            }
        }
        $list_user_id = [];
        $map_wallet = [];
        for ($i = 0; $i < count($roles_limit); $i++) {
            array_push($list_user_id, $roles_limit[$i]['user_id']);
        }
        $list_user_id = array_merge($list_user_id ,$online_invite_user_ids);
        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++) {
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }
        $users = $this->model_user->get_users_by_ids($list_user_id);
        for ($i = 0; $i < count($users); $i++) {
            $users[$i]['diamond_balance'] = intval($map_wallet[$users[$i]['user_id']]['diamond_balance']);
            $users[$i]['charm_balance'] = intval($map_wallet[$users[$i]['user_id']]['charm_balance']);
            $users[$i]['wealth_balance'] = intval($map_wallet[$users[$i]['user_id']]['wealth_balance']);
            $propUseInfo = $this->userPropModel->getPropUseTime($users[$i]['user_id'], 15); // 获取用户是否使用道具
            $users[$i]['user_prop']['hide_info'] = $propUseInfo ? true : false;
            $users[$i]['role_type'] = intval($rolesArr[$users[$i]['user_id']]['role_type']);
        }
        $data_list = [];
        for ($i = 0; $i < count($users); $i++) {
            if(in_array($users[$i]['user_id'] ,$online_invite_user_ids)){
                $online_invite_users[] =  $users[$i];
            }else{
                $data_list[] = $users[$i];
            }
        }
        $data = [];
        $data['list'] = array_values($data_list);
        $data['invite_list'] = $online_invite_users ?? [];
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($roles_count / $page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**添加管理权限
     * @param $room_id
     * @param $user_id
     * @param $current_user_id
     * @return int
     */
    public function add_role($room_id, $user_id ,&$current_user_id)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $current_user_id = $current_user['user_id'];

        $role = $this->model_room->get_role($room_id, $current_user_id);
        if ($role != 2) {
            return Hint::AUTH_ERROR;
        }
        $role_room_count = $this->model_room->get_role_room_count($user_id);
        if ($role_room_count >= 10) {
            return Hint::ROOM_ROLE_ROOM_MAX;
        }
        $invite_user_role = $this->model_room->get_role($room_id, $user_id);
        if($invite_user_role == 1){
            return Hint::ROOM_ROLE_ADMIN;
        }
        $this->model_room->add_role($room_id, $user_id, 1);
        return;
        //临时隐藏功能
        $invite_log = $this->model_room->get_admin_invite_log($room_id ,$user_id);
        if(!empty($invite_log)){
            if((time() - strtotime($invite_log['created_at'])) < 24 * 60 * 60){
                return Hint::ROOM_ROLE_INVITE_AGAIN;
            }else{
                $this->model_room->del_admin_invite_log($room_id ,$user_id);
            }
        }

        $this->model_room->add_admin_invite($room_id ,$current_user_id ,$user_id);
    }

    /**
     * 删除管理权限
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function del_role($room_id, $user_id)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $current_user_id = $current_user['user_id'];

        $role = $this->model_room->get_role($room_id, $current_user_id);
        if ($role != 2) {
            if ($current_user_id != $user_id) {
                return Hint::AUTH_ERROR;
            }
        }
        $this->model_room->del_role($room_id, $user_id);
    }

    public function del_all_role($room_id){
        $this->model_room->del_all_role($room_id);
    }


    /**
     * 获取权限房间
     * @param $user_id
     * @return mixed
     */
    public function get_role_rooms($user_id)
    {

        return $this->model_room->get_role_rooms($user_id);
    }

    public function get_self_role_rooms()
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $data = $this->model_room->get_role_rooms($current_user['user_id']);
        foreach ($data as $k => $v) {
            $data[$k]['opened'] = $this->model_room->get_opened($v['room_id']);
            $data[$k]['allow_open'] = true;

            //$role = $this->model_room->get_role($v['room_id'], $current_user['user_id']);
            //$data[$k]['allow_open'] = false;
            //if ($role != 0){

            //}

            if ($v['certified'] == 0 && $v['business_type'] == 1) {
                unset($data[$k]);
            }
            if (!$data[$k]['opened']) {
                unset($data[$k]);
            }
        }
        $data = array_values($data);
        return $data;
    }


    /**
     * 获取黑名单列表
     * @param $room_id
     * @param $page_index
     * @param $page_size
     * @return array|int
     */
    public function get_blocks($room_id, $page_index, $page_size)
    {

        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $user_id = $current_user['user_id'];

        $role = $this->model_room->get_role($room_id, $user_id);
        if ($role == 0) {
            return Hint::AUTH_ERROR;
        }

        $blocks_count = $this->model_room->get_blocks_count($room_id);
        $blocks_limit = $this->model_room->get_blocks_limit($room_id, $page_index * $page_size, $page_size);

        if(!empty($blocks_limit) > 0){
            $list_user_id = array_column($blocks_limit,'user_id');
            $list_admin_id = array_column($blocks_limit,'admin_id');
            $user_ids = array_merge(array_unique(array_merge($list_user_id,$list_admin_id)));
        }
        $map_wallet = [];

        $wallets = $this->model_userwallet->get_wallets($list_user_id);
        for ($i = 0; $i < count($wallets); $i++) {
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }
        $users = $this->model_user->get_users_by_ids($user_ids);
        $usersMap = array_column($users,null,'user_id');

        $userList = [];
        foreach ($blocks_limit as $info){
            $uid = $info['user_id'];
            $data = $usersMap[$uid] ?? [];
            $data['diamond_balance'] = intval($map_wallet[$uid]['diamond_balance']);
            $data['charm_balance'] = intval($map_wallet[$uid]['charm_balance']);
            $data['wealth_balance'] = intval($map_wallet[$uid]['wealth_balance']);
            $propUseInfo = $this->userPropModel->getPropUseTime($uid, 15); // 获取用户是否使用道具
            $data['user_prop']['hide_info'] = $propUseInfo ? true : false;
            $data['block_time'] = $info['create_timestamp']; //操作时间
            $data['admin'] = new \ArrayObject(); //禁言操作者信息
            if(isset($usersMap[$info['admin_id']])){
               $data['admin'] = [
                   'user_id' => $usersMap[$info['admin_id']]['user_id'] ?? 0,
                   'user_uid' => $usersMap[$info['admin_id']]['user_uid'] ?? "",
                   'nickname' => $usersMap[$info['admin_id']]['nickname'] ?? "",
               ];
            }
            $userList[] = $data;
        }

        $data = [];
        $data['list'] = $userList;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($blocks_count / $page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 添加黑名单
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function add_block($room_id, $user_id)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $current_user_id = $current_user['user_id'];

        $role = $this->model_room->get_role($room_id, $current_user_id);
        if ($role == 0) {
            return Hint::AUTH_ERROR;
        }
        $block_role = $this->model_room->get_role($room_id, $user_id);
        if ($block_role != 0 && $role != 2) {
            return Hint::AUTH_ERROR;
        }

        $this->model_room->add_block($room_id, $user_id, $current_user_id);

    }

    /**
     * 删除黑名单
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function del_block($room_id, $user_id)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $current_user_id = $current_user['user_id'];

        $role = $this->model_room->get_role($room_id, $current_user_id);
        if ($role == 0) {
            return Hint::AUTH_ERROR;
        }
        $this->model_room->del_block($room_id, $user_id);
    }


    /**
     * 获取用户收藏列表
     * @param $page_index
     * @param $page_size
     * @return array|int
     */
    public function get_collects($page_index, $page_size)
    {

        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $user_id = $current_user['user_id'];

        $collects_count = $this->model_room->get_collects_count($user_id);
        $collects_limit = $this->model_room->get_collects_limit($user_id, $page_index * $page_size, $page_size);

        for ($i = 0; $i < count($collects_limit); $i++) {
            $collects_limit[$i]['online_count'] = $this->model_room_user->get_users_count($collects_limit[$i]['room_id']);
            $collects_limit[$i]['opened'] = $this->model_room->get_opened($collects_limit[$i]['room_id']);
        }

        $data = [];
        $data['list'] = $collects_limit;
        $data['page_index'] = $page_index;
        $data['page_count'] = ceil($collects_count / $page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 添加收藏
     * @param $room_id
     * @return int
     */
    public function add_collect($user_id, $room_id)
    {
        $is_collect = $this->model_room->get_collect($room_id ,$user_id);
        if($is_collect){
            return Hint::ROOM_COLLECTED;
        }
        $this->model_room->add_collect($room_id, $user_id);

    }

    /**
     * 删除收藏
     * @param $room_id
     * @return int
     */
    public function del_collect($user_id, $room_id)
    {
        $this->model_room->del_collect($room_id, $user_id);
    }


    /**
     * 获取背景图片列表
     * @return mixed
     */
    public function get_backgrounds()
    {
        $backgrounds = $this->model_room->get_backgrounds();
        return $backgrounds;
    }

    /**
     * 获取背景图片列表
     * @param int $roomId 房间id
     * @return array
     */
    public function get_backgrounds_v2(int $roomId): array
    {
        return $this->model_room->get_backgrounds_v2($roomId);
    }

    /**
     * 设置背景图片
     * @param $room_id
     * @param $pic_url
     * @return int
     */
    public function set_background($room_id, $pic_url)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $now = time();

        do {
            $cur_user = $this->model_user->get_current_user();
            if (empty($cur_user)) {
                $code = Hint::LOGIN_OUT;
                break;
            }
            $cur_id = $cur_user['user_id'];
            $role = $this->model_room->get_role($room_id, $cur_id);
            if ($role == 0) {
                $code = Hint::AUTH_ERROR;
                break;
            }

            $room = $this->model_room->get_room($room_id);
            if(empty($room)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if($room['room_type']['id'] == 46) {
                $code = Hint::PARAM_ERROR;
                $msg = '拍拍房不可修改背景';
                break;
            }

            $this->model_room->set_background_pic($room_id, $pic_url);

            $this->room_msg_services->broadcast_change_background($room_id, $pic_url);

        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 踢出用户
     * @param $room_id
     * @param $user_id
     * @return int
     */
    public function add_shotoff($room_id, $user_id, &$shotoff_time)
    {
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)) {
            return Hint::LOGIN_OUT;
        }
        $cur_id = $cur_user['user_id'];
        $role = $this->model_room->get_role($room_id, $cur_id);
        if ($role == 0) {
            return Hint::AUTH_ERROR;
        }

        $room = $this->model_room->get_room($room_id);
        if (!empty($room) && $room['user_id'] == $user_id) {
            return Hint::AUTH_ERROR;
        }

        // 非房主的管理员不可以踢超管理
        $otherRole = $this->model_room->get_role($room_id, $user_id);
        if($otherRole == 2 && $room['user_id'] != $cur_id) {
            return Hint::AUTH_ERROR;
        }

        // 普通管理员 不能踢 普通管理员
        $otherRole = $this->model_room->get_role($room_id, $user_id);
        if($role == 1 && $otherRole == 1) {
            return Hint::AUTH_ERROR;
        }

        // $shotoff_time = 3600
        $shotoff_time = 5184000;
        $this->model_room->add_shotoff($room_id, $user_id, $shotoff_time);
        $this->model_room->add_shotoff_log($room_id, $cur_user['user_id'], $user_id);
    }


    /**
     * 获取房间列表
     * @param $room_type_id 0.普通 1.电台 2.交友 3.情感 4.娱乐
     * @param $page_index
     * @param $page_size
     * @return array
     */
    public function get_rooms($room_type_id, $page_index, $page_size)
    {
        $rooms_count = $this->model_room->get_rank_count($room_type_id);
        $rooms_limit = $this->model_room->get_rank($room_type_id, $page_index * $page_size, $page_size);

        for ($i = 0; $i < count($rooms_limit); $i++) {
            $rooms_limit[$i]['online_count'] = $this->model_room_user->get_users_count($rooms_limit[$i]['room_id']);
        }

        $data = [];
        $data['list'] = $rooms_limit;
        $data['page_index'] = intval($page_index);
        $data['page_count'] = ceil($rooms_count / $page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 生成首页列表数据
     */
    public function build_rank()
    {
        $rooms = $this->model_room->get_rooms(-1);
        $recommends = $this->model_room->get_recommends();
        $tmpwealth = $this->model_finance_room_wealth->get_rooms_wealth_tmp();
        $data_rooms = [];
        foreach ($rooms as $k => $v) {
            $rank_value = 0;
            $into_time = $this->model_room_hostmicro->get_into_time($v['room_id']);
            if (empty($into_time)) {
                continue;
            }
            $user_count = $this->model_room_user->get_users_count($v['room_id']);
            if ($user_count == 0) {
                continue;
            }
            if (isset($recommends[$v['room_id']])) {
                $rank_value = $rank_value + $recommends[$v['room_id']];
            }
            if (isset($tmpwealth[$v['room_id']])) {
                $rank_value = $rank_value + intval($tmpwealth[$v['room_id']] * 0.1);
            }
            $rank_value = $rank_value + intval($user_count);
            $rooms[$k]['rank_value'] = $rank_value;
            $rooms[$k]['user_count'] = $user_count;
            $rooms[$k]['into_time'] = $into_time;
            if (empty($rank_value)) {
                continue;
            }

            $data_rooms[] = $rooms[$k];
        }
        $this->model_room->set_rank($data_rooms);
    }


    public function get_random_rooms($count)
    {
        $data = $this->model_room->get_rank(-1, 0, $count);
        $ret_data = [];
        foreach ($data as $k => $v) {
            $opened = $this->model_room->get_opened($v['room_id']);
            if ($opened) {
                $ret_data[] = $v;
            }
        }
        return $ret_data;
    }


    /**
     * 获取房间 id数组
     * @param $ids
     * @return array
     */
    public function get_rooms_by_ids($ids)
    {
        if (empty($ids)) {
            return [];
        }
        $ret_data = [];
        $data = $this->model_room->get_rooms_by_ids($ids);
        $data = array_column($data, null, 'room_id');
        foreach ($ids as $v) {
            $data[$v]['hot'] = $this->model_room_hot->get($data[$v]['room_id']);
            $data[$v]['online_count'] = $this->model_room_user->get_users_count($data[$v]['room_id']);
            if (empty($data[$v]['image'])) {
                $roomUser = $this->model_user->get_user($data[$v]['user_id']);
                $data[$v]['image'] = $roomUser['thumbnails'][0] ?? '';
            }
            //设置求陪伴
            $data[$v]['accompany_tag'] = 0;
            if ($this->model_room->getAccompanyTag($data[$v]['room_id'])) {
                $data[$v]['accompany_tag'] = 1;
            }
            //获取小屋主持麦用户的性别
            if($data[$v]['business_type'] == 0){
                $host_user_id = $this->model_room_hostmicro->get_user_id($data[$v]['room_id']);
                if(empty($host_user_id)){
                    $data[$v]['host_mic_gender'] = -1;
                }else{
                    $host_user = $this->model_user->get_user($host_user_id);
                    $data[$v]['host_mic_gender'] = $host_user['gender'];
                }
            }

            //房间是否满了
            $data[$v]['is_full'] = 0;

            $ret_data [] = $data[$v];
        }
        return $ret_data;
    }

    /**
     * 获取热门房间
     * @param $page_index
     * @param $page_size
     * @return array
     */
    public function get_hot_rooms($page_index, $page_size)
    {
        $rooms_count = $this->model_room->get_rank_count(-1);
        $rooms_limit = $this->model_room->get_rank(-1, $page_index * $page_size, $page_size);

        for ($i = 0; $i < count($rooms_limit); $i++) {
            $rooms_limit[$i]['online_count'] = $this->model_room_user->get_users_count($rooms_limit[$i]['room_id']);
        }

        $data = [];
        $data['list'] = $rooms_limit;
        $data['page_index'] = intval($page_index);
        $data['page_count'] = ceil($rooms_count / $page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 获取最新房间
     * @param $page_index
     * @param $page_size
     * @return array
     */
    public function get_new_rooms($page_index, $page_size)
    {
        $rooms_count = $this->model_room->get_rank_count(-1);
        $rooms_limit = $this->model_room->get_rank(-1, $page_index * $page_size, $page_size);

        for ($i = 0; $i < count($rooms_limit); $i++) {
            $rooms_limit[$i]['online_count'] = $this->model_room_user->get_users_count($rooms_limit[$i]['room_id']);
        }

        $data = [];
        $data['list'] = $rooms_limit;
        $data['page_index'] = intval($page_index);
        $data['page_count'] = ceil($rooms_count / $page_size);
        $data['page_size'] = intval($page_size);
        return $data;
    }


    /**
     * 房间类型列表
     * @return array
     */
    public function get_room_types($certified = -1)
    {
        //先从缓存拿，缓存没有取数据库查
        $listData = $this->model_room->get_room_types_from_cache($certified); // add by zxiaofee
        if(!empty($listData)){
            $listData = json_decode($listData, true);
        } else {
            $listData = $this->model_room->get_room_types_simple($certified);
            $this->model_room->set_room_types_to_cache(json_encode($listData), $certified);//设置缓存 add by zxiaofee
        }

        // 处理h5版本分类
        $uaData = $this->parse_app_UA();
        if ($uaData['app'] == 'h5lailai') {
            foreach ($listData as $k => $v) {
                if ($v['id'] == 2) {
                    array_unshift($listData, $v);
                    unset($listData[$k]);
                }
            }
            $listData = array_values($listData);
        }

        if ($uaData['channel_id'] == '800075') {
            foreach ($listData as $k => $v) {
                if ($v['id'] == 2) {
                    unset($listData[$k]);
                }
            }
            $listData = array_values($listData);
        }

        //娱乐房分类可见：安卓、IP非的用户，不受财富值限制
        $user = $this->model_user->get_current_user();
        $status = true;
        if ($uaData['os_name'] == 'Android') {
            $status = getIpAddressInCountryOrCity();
        }
        if ($status) {
            //处理财富等级小于400的
            if(!empty($user)){
                $user_wallet = $this->model_userwallet->get_wallet($user['user_id']);
                if($user_wallet['wealth_balance'] < 400){
                    $filter_data = [];
                    foreach ($listData as $d){
                        //4娱乐房
                        if($d['id'] != 4){
                            $filter_data[] = $d;
                        }
                    }
                    $listData = $filter_data;
                }
            }
        }

        return $listData;
    }

    /**
     * 房间首页图标列表
     * @return mixed
     */
    public function get_room_home_icons()
    {
        return $this->model_room->get_room_home_icons();
    }


    /**
     * 添加举报信息
     * @param $report_room_id
     * @param $report_type
     * @param $pics
     * @param $describe
     * @return bool
     */
    public function add_report($report_room_id, $report_type, $pics, $describe)
    {
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)) {
            return false;
        }
        $user_id = $cur_user['user_id'];
        $this->model_room->add_report($user_id, $report_room_id, $report_type, $pics, $describe);
        return true;
    }

    /**
     * 设置房间类型
     * @param int $room_id 房间ID
     * @param int $type 房间类型 1.电台房间 2.交友 3.情感 4.娱乐
     * @return int
     */
    public function set_room_type($room_id, $type)
    {
        //已认证不能设置
        $room_info = $this->model_room->get_room($room_id);
        if ($room_info['certified'] == 1) {
            return Hint::SUCCESS;
        }

        $roomType = $this->model_room->getRoomType($type);
        if (empty($roomType)) {
            return Hint::ROOM_TYPE_NOT_EXIST;
        }

        if ($room_info['certified'] == 0 && $roomType['certified'] == 1) {
            return Hint::ROOM_TYPE_NOT_ALLOWED;
        }

        //非房主不能设置
        $user_info = $this->model_user->get_current_user();
        $room_role = $this->model_room->get_role($room_id, $user_info['user_id']);
        if ($room_role == 0) {
            return Hint::USER_NOT_OWNER;
        }
        $this->model_room->set_room_type($room_id, $type);

        return Hint::SUCCESS;
    }


    /**
     * 清理待待删除房间
     */
    public function clear_wait_close()
    {
        $room_id = $this->model_room->pop_wait_close();
        if (empty($room_id)) {
            sleep(1);
            return 0;
        }
        $close_timestamp = $this->model_room->get_close_timestamp($room_id);
        if (!empty($close_timestamp) && $close_timestamp < time()) {
            $this->clean($room_id);
            $close_timestamp = null;
        }

        if (empty($close_timestamp)) {
            sleep(1);
            return 0;
        }
        if ($close_timestamp >= time()) {
            $this->model_room->radd_wait_close($room_id);
            sleep(1);
            return 0;
        }
        $this->clean($room_id);
        return $room_id;
    }


    public function loopClose()
    {
        $roomIdArr = $this->model_room->getOpenedRoomIdArr();
        foreach ($roomIdArr as $roomId) {
            $close_timestamp = $this->model_room->get_close_timestamp($roomId);
            if (!empty($close_timestamp) && $close_timestamp < time()) {
                $this->clean($roomId);
            }
        }
    }

    public function clean($room_id)
    {
        $this->model_room->del_open_data($room_id);
        $this->model_room_user->remove($room_id);
        $this->model_room_waitbit->del_users($room_id);
        $this->model_room_hostmicro->remove($room_id);
        $this->model_room_micro->remove($room_id);
        $this->modelRoomMelee->setState($room_id, 0);
        $this->modelRoomTally->close($room_id);
        $this->modelRoomHeart->clean($room_id);
        $this->model_room_micro->removeRoomLockMicro($room_id);
        //删除已开启房间信息
        $this->model_room->delRoomOpenListCache($room_id);
        //删除房间角色
        $this->delRoomRole($room_id);
    }

    public function delRoomRole($room_id) {
        $roles = $this->model_room->getRoles($room_id);
        // 获取房主id
        $roomInfo = $this->model_room->getRoomById($room_id);
        // 获取房间公会信息
        $unionRoom = $this->modelUnion->checkUnionRoom($room_id);
        foreach ($roles as $role) {
            if ($role['user_id'] == $roomInfo['user_id']) {
                continue;
            }
            $this->model_room->del_role_join_room($room_id, $role['user_id']);
            if ($unionRoom) {
                $this->modelUnion->updateUnionRole($unionRoom['un_id'], $role['user_id'], 0);
            }
        }
    }


    /**
     * 关闭房间
     * @param $room_id
     */
    public function close($room_id)
    {
        $cur_user = $this->model_user->get_current_user();
        if (empty($cur_user)) {
            return Hint::LOGIN_OUT;
        }
        $cur_id = $cur_user['user_id'];
        $role = $this->model_room->get_role($room_id, $cur_id);
        if ($role == 0) {
            return Hint::AUTH_ERROR;
        }

        //获取数据
        $roomOpenId = $this->model_room->getRoomOpenList($room_id, 'roomOpenId');
        $host_user_id = $this->model_room_hostmicro->get_user_id($room_id);

        //锁麦
        $microLockList = [];
        for($i = 0; $i < 8; $i++){
            $microLock = $this->model_room_micro->getRoomLockMicro($room_id, $i);
            if(!empty($microLock)) {
                $microLockList[] = $microLock;
            }
        }

        $this->clean($room_id);
        $this->model_room->setRoomMode($room_id, 1);

        //锁麦消息
        foreach($microLockList as $val) {
            $this->msgService->userMicroLockMsg($val['lock_user_id'], $val, 0);
        }

        //删除跨房PK候选池中的数据
        Redis::SREM($this->crossRoomPkRedisList,$room_id);
        //埋点
        $this->tdService->handleTrack('close_room', ['user_id'=>$cur_user['user_id'], 'room_id'=>$room_id, 'roomOpenId'=>$roomOpenId, 'host_user_id'=>$host_user_id]);
    }

    /**
     * 房间是否认证
     * @param int $room_id
     * @return int
     */
    public function is_certified(int $room_id)
    {
        return $this->model_room->is_certified($room_id);
    }

    /**
     * 创建房间音乐
     * @param $roomId
     * @param $musicName
     * @param $musicAuthor
     * @return int
     */
    public function created_room_music($roomId, $musicName, $musicAuthor)
    {
        return $this->model_room_music->createdRoomMusic($roomId, $musicName, $musicAuthor);
    }

    /**
     * 根据房间id获取房间音乐列表
     * @param $roomId
     * @return mixed
     */
    public function get_room_music_list_by_room_id($roomId)
    {
        return $this->model_room_music->getRoomMusicListByRoomId($roomId);
    }


    /**
     * 设置聊天屏幕是否开启
     * @param $room_id
     * @param $opened
     */
    public function set_screen_opened($room_id, $opened)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        if ($role === 0) {
            return Hint::AUTH_ERROR;
        }
        $this->model_room->set_screen_opened($room_id, $opened);
        return true;
    }


    /**
     * 设置房间密码
     * @param $room_id
     * @param $password
     */
    public function set_password($room_id, $password)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        if ($role === 0) {
            return Hint::AUTH_ERROR;
        }
        if ($password === null) {
            $this->model_room->del_password($room_id);
        } else {
            $this->model_room->set_password($room_id, $password);
        }
        return true;
    }

    /**
     * 设置房间总麦是否关闭
     * @param $room_id
     * @param $closed 0.未关闭 1.关闭
     */
    public function set_volume_closed($room_id, $closed)
    {
        $current_user = $this->model_user->get_current_user();
        if (empty($current_user)) {
            return Hint::LOGIN_OUT;
        }
        $role = $this->model_room->get_role($room_id, $current_user['user_id']);
        if ($role === 0) {
            return Hint::AUTH_ERROR;
        }
        $this->model_room->set_volume_closed($room_id, $closed);
        return true;
    }


    /**
     * 获取房间总麦是否关闭
     * @param $room_id
     * @return int
     */
    public function get_volume_closed($room_id)
    {
        return $this->model_room->get_volume_closed($room_id);
    }


    /**
     * 设置名称
     * @param $room_id
     * @param $name
     * @param $apiType
     */
    public function set_name($room_id, $name, $apiType = 0)
    {
        $this->model_room->set_name($room_id, $name, $apiType);
    }

    /**
     * 设置公告
     * @param $room_id
     * @param $notice
     */
    public function set_notice($room_id, $notice)
    {
        $this->model_room->set_notice($room_id, $notice);
    }

    /**
     * 设置说明
     * @param $room_id
     * @param $desc
     */
    public function set_desc($room_id, $desc)
    {
        $this->model_room->set_desc($room_id, $desc);
    }

    /**
     * 设置认证/取消认证
     * @param $room_id
     * @param $val
     */
    public function set_cert($room_id, $val)
    {
        //如果认证状态由整顿中改为已认证，则更新房间积分到默认值
        $oldCertified = $this->model_room->is_certified($room_id);
        if($val == 1 && $oldCertified == 2){
            (new RoomScoreServices())->resetRoomReputation($room_id);
        }

        //设置认证
        $this->model_room->set_cert($room_id, $val);
    }


    /**
     * 设置房间图片
     * @param $room_id
     * @param $image
     */
    public function set_image($room_id, $image)
    {
        $this->model_room->set_image($room_id, $image);
    }


    /**
     * 获取声网token
     * @param $roomId
     * @return null|string
     */
    public function getAgoraToken($roomId)
    {
        $user = $this->model_user->get_current_user();
        if (empty($user)) {
            return null;
        }
        $agora = new agora();
        if ($this->model_room->getAig($roomId)) {
            $agora->aig();
        }
        return $agora->getToken($roomId, $user['user_id']);
    }


    public function getOpenedRoomIdArr()
    {
        $roomIdArr = $this->model_room->getOpenedRoomIdArr();
        return $roomIdArr;
    }


    /**
     * 融云离线状态更新
     * @param $userId
     * @param $ts
     */
    public function setRongCloudOffline($userId, $ts)
    {
        $this->model_user->delOnlineUser($userId);
        $timestamp = $this->model_room->getRongCloudOffline($userId);
        if ($timestamp >= $ts) {
            return;
        }
        $this->model_room->setRongCloudOffline($userId, $ts);
        $this->model_room->pushRongCloudWaitQueue($userId, $ts);
    }

    /**
     * 融云上线状态更新
     * @param $userId
     * @param $ts
     */
    public function setRongCloudOnline($userId, $ts)
    {
        $this->model_user->addOnlineUser($userId, $ts);
        $this->model_room->deleteLogOutUserCache($userId);//删除过期用户的缓存
        $timestamp = $this->model_room->getRongCloudOffline($userId);
        if ($timestamp > $ts) {
            return;
        }
        $this->model_room->delRongCloudOffline($userId);
    }

    /**
     * 获取一个融云超时处理
     */
    public function getRongCloudOfflineTimeout()
    {
        $arr = $this->model_room->popRongCloudWaitQueue();
        if (empty($arr)) {
            return null;
        }
        $userId = $arr['user_id'];
        $timestamp = $arr['timestamp'];
        $nowTimestamp = $this->model_room->getRongCloudOffline($userId);
        if (empty($nowTimestamp)) {
            return null;
        }
        if ($timestamp < $nowTimestamp) {
            return null;
        }
        if (time() * 1000 - $nowTimestamp < 30 * 1000) {
            $this->model_room->pushRongCloudWaitQueue($userId, $nowTimestamp);
            return null;
        }
        $this->model_room->delRongCloudOffline($userId);
        return $userId;
    }

    /**
     * 房间详情
     * */
    public function roomDetail()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $ret = $this->model_room->getSingle($this->requestData, ['room_uid', 'name', 'image'], true);
            if (empty($ret)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '房间' . Hint::getErrCodeMsg($code);
                break;
            }

            $ret['image'] = build_image($ret['image']);
            $data = $ret;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    ################# 后台调用 ##########################################

    /**
     * 房间推荐创建
     * */
    public function roomRecoCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
                $this->I('label_id', '标签ID', 'int', false, '标签ID不能为空');
                $this->I('sort', '排序', 'int', true, '排序不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->model_room->setRoomRecommend($this->requestData);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间推荐更新
     * */
    public function roomRecoUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
                $this->I('label_id', '标签ID', 'int', false, '标签ID不能为空');
                $this->I('sort', '排序', 'int', true, '排序不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $id = $this->requestData['id'];
                // 移除请求数据中的ID
                unset($this->requestData['id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

//                $this->model_room->table = 'room_reco';
                $this->model_room->setRoomRecommend($this->requestData);

                $data['id'] = intval($id);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function getRoomRecommend()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {

                $data = $this->model_room->getRoomRecommend($this->requestData);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间推荐删除
     * */
    public function roomRecoRemove()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '房间ID', 'int', true, '房间推荐ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $ret = $this->model_room->removeRoomRecommend($this->requestData['id']);
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间推荐热度系数创建
     * */
    public function roomRecommendReplace()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
                $this->I('room_uid', '房间显示ID', 'string', true, '房间显示ID不能为空');
                $this->I('coefficient', '热度系数', 'int', true, '热度系数不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->model_room->table = 'room_recommend';

                $roomId = $this->requestData['room_id'];

                // 条件
                $condition = ['room_id' => $roomId];

                // 查询是否存在
                $checkData = $this->model_room->getSingle($condition, ['room_id']);
                if (empty($checkData)) {
                    // 创建
                    $ret = $this->model_room->insertBatch($this->requestData);
                    if (!$ret) {
                        $code = Hint::ERR_DATA_CREATE_FAIL;
                        $msg = '房间推荐热度系数' . Hint::getErrCodeMsg($code);
                        break;
                    }
                } else {
                    // 更新
                    $ret = $this->model_room->singleUpdate($condition, ['coefficient' => $this->requestData['coefficient']]);
                    if (!$ret) {
                        $code = Hint::ERR_DATA_UPDATE_FAIL;
                        $msg = '房间推荐热度系数' . Hint::getErrCodeMsg($code);
                        break;
                    }
                }

                $data['room_id'] = intval($roomId);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间更新
     * */
    public function roomUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
            $this->I('room_uid', '房间号', 'int', false, '房间号不能为空');
            $this->I('room_liang_type', '房间靓号类型', 'int', false, '房间靓号类型不能为空');// 房间靓号类型（0=非靓号，1=靓号）
            $this->I('room_tag', '官方推荐', 'string', false, '官方推荐不能为空');// URL
            $this->I('room_rate', '房间兑换比例', 'int', false, '房间兑换比例不能为空');
            $this->I('heart', '是否有心动房功能', 'int', false, '是否有心动房功能不能为空');// 0=否 1=是
            $this->I('turntable', '是否转盘功能', 'int', false, '是否转盘功能不能为空');// 0=否 1=是
            $this->I('pk', '是否转盘功能', 'int', false, '是否pk功能不能为空');// 0=否 1=是
            $this->I('spanpk', '是否spanpk功能', 'int', false, '是否spanpk功能不能为空');// 0=否 1=是
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $roomId = $this->requestData['room_id'];
            // 移除请求数据中的ID
            unset($this->requestData['room_id']);

            if (empty($this->requestData)) {
                $code = Hint::ERR_PARAMS_CHECK_FAIL;
                $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                break;
            }

            // 查询是否存在此房间UID
            $roomUid = $this->requestData['room_uid'] ?? 0;
            if (!empty($roomUid)) {
//                if (strlen($roomUid) <> 5) {
//                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
//                    $msg = '房间号只能是五位数';
//                    break;
//                }
//                if (!filterUUID($roomUid) or strlen($roomUid) <> 5) {
//                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
//                    $msg = '房间号只能是靓号并且五位数';
//                    break;
//                }

                $checkRoomData = $this->model_room->getSingle(['room_uid' => $roomUid], ['room_id', 'room_uid'], true);
                if (!empty($checkRoomData) and $checkRoomData['room_id'] == $roomUid) {
                    $code = Hint::ERR_DATA_EXIST;
                    $msg = '房间UID：' . $roomUid . ' ' . Hint::getErrCodeMsg($code);
                    break;
                }
            }

            $this->model_room->singleUpdate(['room_id' => $roomId], $this->requestData);

            $data['room_id'] = $roomId;

            // 删除房间缓存数据
            $this->model_room->delCache($roomId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间举报处理更新
     * */
    public function reportUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '举报ID', 'int', true, '举报ID不能为空');
                $this->I('dispose', '处理类型', 'int', true, '处理类型不能为空');// 0:未处理 1:已处理
                $this->I('dispose_desc', '处理说明', 'string', true, '处理说明不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $id = $this->requestData['id'];
                // 移除请求数据中的ID
                unset($this->requestData['id']);

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                $this->model_room->table = 'room_report';
                $ret = $this->model_room->singleUpdate(['id' => $id], $this->requestData);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '房间' . Hint::getErrCodeMsg($code);
                    break;
                }

                $data['id'] = intval($id);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间图片审核
     * */
    public function roomImageExamine()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('id', '审核数据ID', 'int', true, '审核数据ID不能为空');
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
            $this->I('status', '审核状态（0=未审核，1=已审核，2=驳回）', 'int', true, '审核状态不能为空');
            $this->I('remark', '审核备注', 'string', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            if (!in_array($this->requestData['status'], [1, 2])) {
                $code = Hint::ERR_NORMAL;
                $msg = Hint::getErrCodeMsg($code) . ':审核状态';
                break;
            }

            // 查询房间封面未审核数据
            $checkImageData = $this->model_room->getRoomImageExamine(['room_id' => $this->requestData['room_id'], 'type' => 0, 'status' => 0]);
            if (empty($checkImageData)) {
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '房间封面未审核' . Hint::getErrCodeMsg($code);
                break;
            }

            // 更新房间封面审核数据状态
            $updateRoomImageExamine = $this->model_room->updateRoomImageExamine($checkImageData['id'], $checkImageData['room_id'], $this->requestData['status'], ($this->requestData['remark'] ?? ''));
            if (!$updateRoomImageExamine) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '图片审核' . Hint::getErrCodeMsg($code);
                break;
            }

            // TODO 只有在审核通过才更新房间图片
            if (in_array($this->requestData['status'], [1])) {
                // 设置图片 (将真实更新到房间数据表中)
                $setImage = $this->model_room->set_image($checkImageData['room_id'], $checkImageData['image']);
                if (!$setImage) {
                    $code = Hint::ERR_FAIL;
                    $msg = '房间封面设置' . Hint::getErrCodeMsg($code);
                    break;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间标签创建
     * */
    public function roomTagCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('room_type_id', '房间分类ID', 'int', true, '房间分类ID不能为空');
            $this->I('tag_name', '标签名称', 'string', true, '标签名称不能为空');
            $this->I('tag_color', '标签颜色', 'string', true, '标签颜色不能为空');
            $this->I('status', '状态', 'int', false, '状态不能为空');// 状态（0=已删除，1=正常）数据库默认1=正常

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $this->model_room->table = 'room_tag';
            $id = $this->model_room->insertSingle($this->requestData);
            if ($id <= 0) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = '标签' . Hint::getErrCodeMsg($code);
                break;
            }

            $data['id'] = intval($id);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间标签更新
     * */
    public function roomTagUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('id', '标签数据ID', 'int', true, '标签数据ID不能为空');
            $this->I('room_type_id', '房间分类ID', 'int', false, '房间分类ID不能为空');
            $this->I('tag_name', '标签名称', 'string', false, '标签名称不能为空');
            $this->I('tag_color', '标签颜色', 'string', false, '标签颜色不能为空');
            $this->I('status', '状态', 'int', false, '状态不能为空');// 状态（0=已删除，1=正常）

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $id = $this->requestData['id'];
            // 移除请求数据中的ID
            unset($this->requestData['id']);

            if (empty($this->requestData)) {
                $code = Hint::ERR_PARAMS_CHECK_FAIL;
                $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                break;
            }

            $this->model_room->table = 'room_tag';
            $ret = $this->model_room->singleUpdate(['id' => $id], $this->requestData);
            if (!$ret) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '标签' . Hint::getErrCodeMsg($code);
                break;
            }

            $data['id'] = $id;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * CBD房间创建
     * */
    public function createRoomByCBD()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $adminName = $this->requestData['admin_name']??'';
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');
            $this->I('business_type', '商业类型', 'int', false, '商业类型不能为空'); // 商业类型（0=小屋，1=CBD）
            $this->I('room_type', '房间类型', 'int', true, '房间类型不能为空');
            $this->I('tally', '是否计数', 'int', false, '是否计数不能为空');
            $this->I('coefficient', '推荐系数', 'int', false, '推荐系数不能为空');


            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $businessTypeDesc = ['小屋', 'CBD'];

            // 默认创建为CBD
            $businessType = $this->requestData['business_type'] ?? 1;

            // 查询是否存在此用户房间
            /*$checkRoomData = $this->model_room->getSingle(['user_id'=>$this->requestData['user_id'],'business_type' => $businessType],['*'],true);
            if(!empty($checkRoomData) and $checkRoomData['business_type'] == $businessType){
                $code = Hint::ERR_DATA_EXIST;
                $msg = '该用户的'.$businessTypeDesc[$businessType].'房间' . Hint::getErrCodeMsg($code);
                break;
            }*/

            // 取出房间ID池中已生成的房间UID
            $roomUid = $this->model_room->generatedRoomUid();
            if (empty($roomUid)) {
                $code = Hint::ERR_FAIL;
                $msg = '房间ID池已空，请先灌满房间ID池后再次生成';
                break;
            }

            // 查询用户信息
            $userData = $this->model_user->get_user($this->requestData['user_id']);
            $image = $userData['images'][0] ?? '';
            if (!empty($image)) {
                $image = parse_url($image)['path'] ?? '';
            }

            DB::beginTransaction();

            // 创建房间数据 默认为认证
            $roomId = $this->model_room->create_room([
                'user_id' => $this->requestData['user_id'],
                'room_uid' => $roomUid,
                'image' => $image,
                'business_type' => $businessType,
                'certified' => 1,
                'room_type' => $this->requestData['room_type']
            ]);

            if ($roomId <= 0) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $updateData = [
                'heart' => $this->requestData['heart'],
                'pk' => $this->requestData['pk'],
                'spanpk' => $this->requestData['spanpk'],
                'melee' => $this->requestData['melee'],
                'tally' => $this->requestData['tally'],
                'turntable' => $this->requestData['turntable'],
                'room_tag' => $this->requestData['room_tag'],
            ];
            //电台房间默认不开启计数
            if($this->requestData['room_type'] == 44){
                $updateData['tally'] = 0;
            }
            $this->model_room->table = 'room';
            $this->model_room->singleUpdate(['room_id' => $roomId], $updateData);

            // 添加房间默认管理员
            $this->model_room->add_role($roomId, $this->requestData['user_id'], 2);
            // 初始化房间财富值
            $this->model_finance_room_wallet->add_wallet($roomId);
            // 添加收藏
            $this->model_room->add_collect($roomId, $this->requestData['user_id']);
            //设置房间推荐系数
            if($this->requestData['coefficient'] > 0) {
                //修改推荐系数
                $info = $this->model_room->updateRoomCoefficient($roomId, $this->requestData['coefficient']);
            }

            DB::commit();
            $this->model_room->addRoomAdmin($roomId,$adminName);
            $data['room_id'] = intval($roomId);
            $data['room_uid'] = intval($roomUid);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * CBD房间修改
     * */
    public function updateRoomByCBD()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $adminName = $this->requestData['admin_name']??'';
            $this->I('room_id', 'room_id', 'int', true, 'room_id不能为空');
            $this->I('room_uid', 'room_uid', 'int', true, 'room_uid不能为空');
            $this->I('room_type', '房间类型', 'int', true, '房间类型不能为空');
            $this->I('tally', '是否计数', 'int', false, '是否计数不能为空');
            $this->I('coefficient', '推荐系数', 'int', false, '推荐系数不能为空');
            $this->I('vote', '是否投票', 'int', false, '是否投票不能为空');
            $this->I('background_pic','房间背景','string',false,'房间背景');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $this->model_room->addRoomAdmin($this->requestData['room_id'],$adminName);

            DB::beginTransaction();
            //电台房间默认不开启计数
            if($this->requestData['room_type'] == 44){
                $this->requestData['tally'] = 0;
            }
            //拍拍房
            if($this->requestData['room_type'] == 46){
                $this->requestData['background_pic'] = '/rank/paipai/background.png';
            }
            //修改房间
            $this->model_room->table = 'room';
            $roomId = $this->requestData['room_id'];
            $coefficient = $this->requestData['coefficient'];
            unset($this->requestData['room_id'], $this->requestData['coefficient']);
            $this->model_room->singleUpdate(['room_id' => $roomId], $this->requestData);

            //修改推荐系数
            $info = $this->model_room->updateRoomCoefficient($roomId, $coefficient);

            //删除房间redis缓存
            $this->model_room->delRedisCache($roomId);

            DB::commit();

        } while (false);

        return compact('code', 'msg', 'data');
    }


    public function setTopic()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('room_id', '房间推荐ID', 'int', true, '房间推荐ID不能为空');
                $this->I('topic', '房间推荐ID', 'string', true, '房间话题不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                //extract($variables); //数组参数化
                $room_id = $this->requestData['room_id'];
                $topic = $this->requestData['topic'];
                $this->model_room->setTopic($room_id, $topic);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }


    public function getShotoffLog()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('room_id', '房间ID', 'int', true, '房间id不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                //extract($variables); //数组参数化
                $room_id = $this->requestData['room_id'];
                $retdata = $this->model_room->getShotoffLog($room_id);
                if (empty($retdata)) {
                    break;
                }
                $userIdArr = array_column($retdata, 'user_id');
                $shotoffUserIdArr = array_column($retdata, 'shotoff_user_id');
                $userIdArr = array_unique(array_merge($userIdArr, $shotoffUserIdArr));
                $userArr = $this->model_user->get_users_by_ids($userIdArr);
                $userData = array_column($userArr, null, 'user_id');
                foreach ($retdata as $key => $val) {
                    $retdata[$key]['user'] = $userData[$val['user_id']];
                    $retdata[$key]['shotoff_user'] = $userData[$val['shotoff_user_id']];
                    $retdata[$key]['shotoff_user']['nickname'] = $this->userPropModel->getPropUseTime($val['shotoff_user_id'], 15) ? "神秘人" : $retdata[$key]['shotoff_user']['nickname'];
                    unset($retdata[$key]['user_id']);
                    unset($retdata[$key]['shotoff_user_id']);
                }
                $data = $retdata;
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 处理房间审核数据
     * @param $roomId
     * @param $data 房间数据
     * @return array
     */
    public function roomContentCheckHandle($roomId, $data)
    {
        //查询审核相关数据是否存在
        $contentCheckList = $this->contentCheckModel->getContentCheckListByDataIdAndCheckObj($roomId, [3, 4, 5, 7]);
        foreach ($contentCheckList as $key => $value) {
            if ($value['check_obj'] == 3) {
                $data['name'] = $value['content'];
            }

            if ($value['check_obj'] == 4) {
                $data['notice'] = $value['content'];
            }

            if ($value['check_obj'] == 5) {
                $data['desc'] = $value['content'];
            }

//            if ($value['check_obj'] == 7) {
//                $data['image'] = $value['content'];
//            }
        }

        return $data;
    }

    /*
     * 小屋新版本房间类型信息获取
     * */
    public function getRoomNewTypes()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('certified', '房间ID', 'int', false, 'certified不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                //extract($variables); //数组参数化

                $roomTypeCate = $this->model_room->getRoomTypeCate(0);

                foreach ($roomTypeCate as $key => $value) {
                    $roomTypeCate[$key]['data'] = isset($value['cate_id']) ? $this->model_room->getRoomNewTypes(0, $value['cate_id']) : [];
                }

                $data = $roomTypeCate;
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间类型-更新或创建
     * */
    public function updateOrInsertRoomType()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('type_id', 'type_id', 'int', false);
            $this->I('type_name', 'type_name', 'string', false);
            $this->I('img_home_url', '首页显示图片', 'string', false);
            $this->I('img_room_url', '房间内显示图片', 'img_room_url', false);
            $this->I('img_roomedit_url', '房间编辑显示图片', 'string', false);
            $this->I('img_room_fast_url3', '速配入口图片', 'string', false);
            $this->I('img_room_fast_url', '速配入口图片', 'string', false);
            $this->I('img_cbd_url', 'cbd页面icon', 'string', false);
            $this->I('sort', 'sort', 'int', false);
            $this->I('certified', '是否是认证使用', 'int', false);
            $this->I('area', '区服', 'string', false);
            $this->I('level', '段位', 'string', false);
            $this->I('title', '口号', 'string', false);
            $this->I('model_str', 'model_str', 'string', false);
            $this->I('mode_type', 'mode_type', 'int', false);
            $this->I('cate_id', 'cate_id', 'int', false);
            $this->I('is_show', 'is_show', 'int', false);
            $this->I('location', '展示位置', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $typeId = $this->requestData['type_id'] ?? 0;
            unset($this->requestData['type_id']);

            // 更新
            if ($typeId > 0) {
                $ret = $this->model_room->CUDRoomType($this->requestData, 'update', $typeId);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '房间类型' . Hint::getErrCodeMsg($code);
                    break;
                }
                $data['type_id'] = $typeId;
                break;
            } else {
                if (empty($this->requestData['type_name']) || !isset($this->requestData['certified'])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '房间类型' . Hint::getErrCodeMsg($code);
                    break;
                }

                //获取最新type_id
                $typeId = $this->model_room->getRoomTypeLastId();
                if (!$typeId) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '房间类型' . Hint::getErrCodeMsg($code);
                    break;
                }
                $this->requestData['type_id'] = $typeId;
            }

            // 创建
            $ret = $this->model_room->CUDRoomType($this->requestData, 'insert');
            if (!$ret) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = '房间类型' . Hint::getErrCodeMsg($code);
                break;
            }
            $data['type_id'] = intval($typeId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 房间类型-删除
     * */
    public function delRoomType()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('type_id', 'type_id', 'int', true, 'type_id不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $typeId = $this->requestData['type_id'] ?? 0;
                // 删除
                $ret = $this->model_room->CUDRoomType([], 'delete', $typeId);
                if (!$ret) {
                    $code = Hint::ERR_DATA_REMOVE_FAIL;
                    $msg = '房间类型' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function setFreeMicro($room_id, $free_micro)
    {
        $this->model_room->set_freemicro($room_id, $free_micro);
    }

    # ------------------------------------------------------------------------------------------

    /**
     * 根据房间ID获取麦上用户信息列表
     *
     * @param array $requestData 请求参数
     * @return array
     * */
    public function microUserList($requestData)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [
            'host_micro' => [],
            'general_micro_list' => [],
        ];

        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');

            $checkParams = $this->check($requestData); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $roomIsOpen = $this->model_room->get_opened($requestData['room_id']);
            if (!$roomIsOpen) {
                $code = Hint::ROOM_NOT_OPEN;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            // TODO 用户ID组
            $userIdArray = [];

            // 判断当前用户是否主持人麦
            $roomHostMicroUserId = $this->model_room_hostmicro->get_user_id($requestData['room_id']);
            if (empty($roomHostMicroUserId)) {
                $code = Hint::ROOM_HOSTMICRO_IS_NULL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $userIdArray[] = $roomHostMicroUserId;

            // 获取麦列表用户
            $microUser = $this->model_room_micro->get_micros($requestData['room_id'], 0);
            $microUserList = [];
            foreach ($microUser as $key => $value) {
                if (empty($value['user_id'])) {
                    continue;
                }
                $microUserList[$value['user_id']] = $value;
            }
            /*if (empty($microUserList)) {
                $code = Hint::ROOM_MICRO_IS_NULL;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }*/

            if (!empty($microUserList)) {
                /*if (count($microUserList) >= 8) {
                    array_pop($microUserList);
                }*/
                $userIdArray = array_merge($userIdArray, array_keys($microUserList));
            }

            // 获取用户信息
            $userList = $this->model_user->get_users_by_ids($userIdArray);
            foreach ($userList as $key => $value) {
                if ($value['user_id'] == $roomHostMicroUserId) {
                    $data['host_micro'] = [
                        'microphone_id' => 0,
                        'user_id' => $value['user_id'],
                        'nickname' => $value['nickname'],
                        'image' => $value['images'][0] ?? '',
                        'gender' => $value['gender'],
                    ];
                    continue;
                }

                if (array_key_exists($value['user_id'], $microUserList)) {
                    $data['general_micro_list'][] = [
                        'microphone_id' => $microUserList[$value['user_id']]['microphone_id'],
                        'user_id' => $value['user_id'],
                        'nickname' => $value['nickname'],
                        'image' => $value['images'][0] ?? '',
                        'gender' => $value['gender'],
                    ];
                    continue;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取用户是否在麦上状态
     *
     * @param array $requestData 请求参数
     * @return array
     * */
    public function getMicroUserState($requestData)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [
            'state' => 0,// 是否在麦上（0=否，1=是）
        ];

        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');

            $checkParams = $this->check($requestData); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $roomIsOpen = $this->model_room->get_opened($requestData['room_id']);
            if (!$roomIsOpen) {
                $code = Hint::ROOM_NOT_OPEN;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            // 获取用户上麦状态
            $getUserMicroStatus = $this->model_room_micro->get_user_micro_status($requestData['room_id'], $requestData['user_id']);
            if (empty($getUserMicroStatus)) {
                break;
            }

            $data['state'] = $getUserMicroStatus['status'];
            $data['microphone_id'] = $getUserMicroStatus['micro_id'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //获取当前用户的权限
    public function get_user_role($requestData){
        return $this->model_room->get_role($requestData['room_id'] ,$requestData['user_id']);
    }


    /**小屋速配便捷入口
     * @return array
     */
    public function getRoomFastType()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $data = $this->model_room->getFastTypes();

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }
    public function get_user_room_id($user_id){
        return $this->model_room->get_user_room_id($user_id);
    }

    public function getIsGameRoom($type_id){
        return $this->model_room->getIsGameRoom($type_id);
    }

    public function getOnlineTime(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $SevenBeforeTime = strtotime(date('Y-m-d 00:00:00', strtotime('-8 day')));
            $yesterdayTime = strtotime(date('Y-m-d 00:00:00'));
            $data['history'] = $this->model_room->getRoomOnlineTime($this->requestData['room_id'] ,$SevenBeforeTime ,$yesterdayTime);
            $data['today'] = $this->model_room->getRoomOnlineTime($this->requestData['room_id']);
        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function setCarStatus(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', 'room_id', 'int', true);
            $this->I('fleet_king', 'fleet_king', 'int', true);
            $this->I('fleet_peace', 'fleet_peace', 'int', true);
            $this->I('fleet_mult', 'fleet_mult','int' , true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $room_id = $this->requestData['room_id'];
            unset($this->requestData['room_id']);
            $data = $this->model_room->updateCarStatus($room_id ,$this->requestData);

        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function addChatPrivateLog(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', 'room_id', 'string', true);
            $this->I('to_user_id', 'to_user_id','int' , true);
            $this->I('user_id', 'user_id', 'int', true);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            if(!is_numeric($this->requestData['room_id'])){
                break;
            }
            extract($variables); //数组参数化

            $user_id = $this->requestData['user_id'];
            $room_id = $this->requestData['room_id'];
            $to_user_id= $this->requestData['to_user_id'];
            if(empty($room_id) || empty($to_user_id)){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $data = $this->model_room->insertChatPrivateLog($room_id ,$user_id ,$to_user_id);

        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function addJoinLog($room_id ,$user_id, $isSearch){
        if(!empty($room_id) && !empty($user_id) && is_numeric($room_id)){
            $this->model_room->insertJoinLog($room_id ,$user_id, $isSearch);
            try{
                // 判断该房间是否有直播计划
                $plan = $this->model_room->getNewRoomLivePlanByRoomId($room_id);
                if(!$plan || !is_numeric($plan[0]['id'])) return 0;
                $userRegisterLogModel = new UserRegisterLog();
                $userRegisterLog = $userRegisterLogModel->getUserRegisterLog($user_id);

                // 注册时间是否在注册时间内
                if($userRegisterLog->time < $plan[0]['start_time'] || $userRegisterLog->time > $plan[0]['end_time']) return 0;
                if(!$userRegisterLog || $userRegisterLog->platform === 'kol' || $userRegisterLog->platform === 'koc') return 0;

                // 判断该用户是否是一个有效的直播用户
                $activePlan = $this->model_room->effectiveSearchUser($plan[0]['id'], $user_id);
                if(!$activePlan) return 0;

                // 计划跟参与用户唯一
                $this->model_room->insertRoomLivePlanActive([
                    'plan_id' => $activePlan['plan_id'],
                    'join_user_id' => $activePlan['join_user_id'],
                    'create_time' => time()
                ]);
            }catch(Exception $e) {
                Log::debug('记录有效搜索用户', [ 'message' => $e->getMessage() ]);
            }
        }
    }

    //房间标签删除
    public function labelDel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('id', '标签主键ID', 'string', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $this->roomRecommendLabel->delLabel($this->requestData['id']);
        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function share(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', '房间id', 'int', true);
            $this->I('user_id', '用户id', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $this->model_room->addShare($this->requestData['room_id'] ,$this->requestData['user_id']);

        }while(false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 商品标签创建
     */
    public function labelCreate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('name', '标签名称', 'string', true, '标签名称不能为空');
                $this->I('animate_resource', '标签图片', 'string', false, '标签图片');
                $this->I('new_animate_resource', 'svga标签', 'string', false, 'svga标签');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->model_room->table = 'room_recommend_label';
                $data['label_id'] = $this->model_room->insertSingle($this->requestData);
                if ($data['label_id'] <= 0) {
                    $code = Hint::ERR_DATA_CREATE_FAIL;
                    $msg = '房间标签' . Hint::getErrCodeMsg($code);
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 商品标签编辑
     * @return array
     */
    public function labelEdit()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('id', '标签ID', 'string', true, '标签ID不能为空');
                $this->I('name', '标签名称', 'string', true, '标签名称不能为空');
                $this->I('animate_resource', '标签图片', 'string', false, '标签图片');
                $this->I('new_animate_resource', '标签svga', 'string', false, '标签svga');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $this->model_room->table = 'room_recommend_label';
                $id = $this->requestData['id'];
                unset($this->requestData['id']);
                $this->model_room->singleUpdate(['id' => $id], $this->requestData);
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 添加或修改房间标签
     * */
    public function insertOrUpdateLabel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');
                $this->I('label_id', '标签ID', 'int', false, '标签ID不能为空');
                $this->I('starttime', '开始时间', 'string', false);
                $this->I('endtime', '结束时间', 'string', false);
                $this->I('special_recommend_resource_url', '特殊推荐标签资源', 'string', false);
                $this->I('special_recommend_start_time', '特殊推荐标签开始时间', 'string', false);
                $this->I('special_recommend_end_time', '特殊推荐标签结束时间', 'string', false);

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                if (empty($this->requestData)) {
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                    break;
                }

                $this->model_room->setRoomRecommend($this->requestData ,false);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //房间标签删除
    public function delRoomLabel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', '房间id', 'string', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $data = $this->model_room->delRoomLabel($this->requestData['room_id']);
        }while(false);
        return compact('code', 'msg', 'data');
    }

    //去掉未认证房间管理
    public function cmsCancelRole()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', '房间ID', 'int', true);
            $this->I('user_id', '用户ID', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $room = $this->model_room->get_room($this->requestData['room_id']);
            if($room['certified'] ==1){
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $role = $this->model_room->get_role($this->requestData['room_id'], $this->requestData['user_id']);
            if ($role == 2) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $this->model_room->del_role($this->requestData['room_id'], $this->requestData['user_id']);
        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function timingHandleLabel(){
        $this->model_room->handleRoomLabel();
    }

    public function get_rooms2_by_ids($ids)
    {
        if (empty($ids)) {
            return [];
        }

        $ret_data = [];
        $data = $this->model_room->get_rooms_by_ids($ids);
        $roomLabelRes = $this->model_room->getRoomLableByRoomIds($ids);
        $roomLabelMap = array_column($roomLabelRes, null, 'room_id');
        $data = array_column($data, null, 'room_id');

        // 房间日榜第一
        $dayRankTop1 = $this->model_finance_room_wealth->get_room_charts(1,0,1);
        $dayRankTop1 = array_keys($dayRankTop1);

        // 房间日榜icon
        $dayRankLabel = $this->model_room->getRoomRecommendLabelById(3, [ 'new_animate_resource', 'animate_resource' ]);

        foreach ($ids as $index => $v) {
            //获取房间动态背景
            $roomInfo = $this->model_room->get_room($v);
            $data[$v]['dynamic_cover'] = $roomInfo['dynamic_cover'];
            //获取房间Pk spanPkId
            $data[$v]['pk_status'] = '';

            $tmpRoomUserAvatar = [];
            //获取主持麦头像
            $hostMicroId = $this->model_room_hostmicro->get_user_id($v);
            $hostMicroInfo = $this->model_user->get_user($hostMicroId);
            if ($hostMicroInfo) {
                $tmpRoomUserAvatar[] = [ 'pic' => $hostMicroInfo['thumbnails'], 'gender' => $hostMicroInfo['gender'], 'adapt_images' => isset($hostMicroInfo['images'][0]) && $hostMicroInfo['images'][0] ? $hostMicroInfo['images'][0].'?x-oss-process=image/resize,w_60,m_lfit' : '' ];
                $data[$v]['hostMicroAva'] = $this->mallGoods->getGoodsAttire($hostMicroId);
            }
            //获取房间在线用户
            $inRoomUserId = $this->model_room_user->get_usersids($v);
            $inRoomUserIdSlice = array_slice($inRoomUserId, 0, 20);
            if (count($inRoomUserIdSlice) > 0) {
                foreach ($inRoomUserIdSlice as $uId) {
                    if(!empty($hostMicroId) && $hostMicroId==$uId) {
                        continue;
                    }
                    $roomUserInfo = $this->model_user->get_user($uId);
                    $tmpRoomUserAvatar[] = [ 'pic' => $roomUserInfo['thumbnails'], 'gender' => $roomUserInfo['gender'], 'adapt_images' => isset($roomUserInfo['images'][0]) && $roomUserInfo['images'][0] ? $roomUserInfo['images'][0].'?x-oss-process=image/resize,w_60,m_lfit' : ''];
                }
            }
            $data[$v]['online_list'] = $tmpRoomUserAvatar;
            $data[$v]['hot'] = $this->model_room_hot->get($data[$v]['room_id']);
            $data[$v]['online_count'] = $this->model_room_user->get_users_count($data[$v]['room_id']);
            // if (empty($data[$v]['image'])) {
                $roomUser = $this->model_user->get_user($data[$v]['user_id']);
                if(empty($data[$v]['image'])) $data[$v]['image'] = $roomUser['thumbnails'][0] ?? '';
                $data[$v]['gender'] = $roomUser['gender'] ?? 0;
            // }
            //设置求陪伴
            $data[$v]['accompany_tag'] = 0;
            if ($this->model_room->getAccompanyTag($data[$v]['room_id'])) {
                $data[$v]['accompany_tag'] = 1;
            }
            //获取所有在麦上的用户头像
            $host_mic_user_id = $this->model_room_hostmicro->get_user_id($data[$v]['room_id']);
            $host_user = $this->model_user->get_user($host_mic_user_id);
            $mics_images = [];
            if(!empty($host_user['images'])){
                $mics_images[] = $host_user['images'][0];
            }
            $mic_users = $this->model_room_micro->get_micros($data[$v]['room_id'] ,$data[$v]['room_type']['id']);
            foreach ($mic_users as $mic_user){
                if(!empty($mic_user['user_id'])){
                    $val = $this->model_user->get_user($mic_user['user_id']);
                    if(!empty($val['images'])){
                        $mics_images[] = $val['images'][0];
                    }
                }
            }
            $data[$v]['mic_images'] = $mics_images ?? [];

            //在线用户
            $online_user_ids = $this->model_room_user->get_usersids($data[$v]['room_id']);
            $data[$v]['online_man_count'] = 0;
            foreach ($online_user_ids as $online_user_id){
                if($this->model_user->get_user($online_user_id)['gender'] == 1){
                    $data[$v]['online_man_count'] ++;
                }
            }
            $data[$v]['online_woman_count'] = $data[$v]['online_count'] - $data[$v]['online_man_count'] ;

            // 后台配置的优先级大于自动配置
            $data[$v]['recommend_label'] = '';
            $data[$v]['recommend_svag'] = '';
            $data[$v]['recommend_special'] = '';

            if(in_array($v, $dayRankTop1)) {
                $data[$v]['recommend_label'] = $dayRankLabel['animate_resource'] ?? '';
                $data[$v]['recommend_svag'] = $dayRankLabel['new_animate_resource'] ?? '';
            }

            if(isset($roomLabelMap[$v])) {
                $data[$v]['recommend_label'] = $roomLabelMap[$v]['animate_resource'];
                $data[$v]['recommend_svag'] = $roomLabelMap[$v]['new_animate_resource'];
                $data[$v]['recommend_special'] = $roomLabelMap[$v]['special_animate_resource'];
            }
            $ret_data [] = $data[$v];


        }

        return $ret_data;
    }


    public function adminApply(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', '房间ID', 'int', true);
            $this->I('user_id', '用户ID', 'int', true);
            $this->I('status' ,'状态' ,'int' ,true); //1同意 2拒绝
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $user_id = $this->requestData['user_id'];
            $invite_log = $this->model_room->get_admin_invite_log($this->requestData['room_id'],$user_id);
            if(empty($invite_log)){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $this->model_room->del_admin_invite_log($this->requestData['room_id'] ,$user_id);
            $room = $this->model_room->get_room($this->requestData['room_id']);
            $data['send_user_id'] = $room['user_id'];
            if($this->requestData['status'] == 2){
                break;
            }
            $role_room_count = $this->model_room->get_role_room_count($user_id);
            if ($role_room_count >= 10) {
                $code = Hint::ROOM_ROLE_ROOM_MAX;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $user_role = $this->model_room->get_role($this->requestData['room_id'], $user_id);
            if($user_role == 1){
                $code = Hint::ROOM_ROLE_ADMIN;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $this->model_room->add_role($this->requestData['room_id'] ,$user_id ,1);
        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function setDynamicBackground(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', '房间ID', 'int', true);
            $this->I('end_time', '结束时间', 'string', true);
            $this->I('dynamic_id' ,'动态封面地址' ,'int' ,false);
            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化
            $time_interval = strtotime($this->requestData['end_time'])-time();
            if($time_interval <0){
                $code = Hint::PARAM_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }
            $room = $this->model_room->get_room($this->requestData['room_id']);
            if(empty($room)){
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '房间-'.Hint::getErrCodeMsg($code);
                break;
            }
            $dynamic_id = $this->requestData['dynamic_id'] ?? 1;
            $dynamic = $this->model_room->get_dynamic($dynamic_id);
            if(empty($dynamic['url'])){
                $code = Hint::ERR_DATA_NOT_EXIST;
                $msg = '资源-'.Hint::getErrCodeMsg($code);
                break;
            }
            //添加 动态 房间记录数据库$room_id,$dynamic_id,$start_time,$end_time
            $this->model_room_dynamic_log->createRoomDyLog($this->requestData['room_id'],$dynamic_id,$this->requestData['end_time']);
            $this->model_room->setDynamic($this->requestData['room_id'] ,$dynamic['url'] ,$time_interval);
        }while(false);

        return compact('code', 'msg', 'data');
    }

    # ------------------------------------------------------------------------------------------

    public function createOrUpdateRoomLivePlan(array $data = []) {
        $id = $data['id'] ?? 0;
        if($id > 0) {
            return $this->model_room->updateRoomLivePlan($id, $data);
        } else {
            return $this->model_room->createRoomLivePlan($data);
        }
    }

    public function deleteRoomLivePlan(string $id = '') {
        return $this->model_room->removeRoomLivePlan($id);
    }

    public function getWealth(int $roomId) {
        return $this->model_finance_room_wallet->get_wallet($roomId);
    }

    public function setGodHaoSwitch(int $roomId = 0, int $switch = 0) {
        return $this->model_room->setGodHaoSwitch($roomId, $switch);
    }

    public function pushInfo(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = null;
        do {
            $this->I('room_id', '房间ID', 'int', true);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            extract($variables); //数组参数化
            $data = $this->model_room->get_room($this->requestData['room_id']);
            if (empty($data)) {
                $code = Hint::ROOM_NO_EXIST; //房间不存在
                $msg = Hint::getErrCodeMsg($code);
                $data = null;
            }
            $status = $this->model_room->get_opened($this->requestData['room_id']);
            if(!$status){
                $code = Hint::ROOM_NOT_OPEN;
                $msg = Hint::getErrCodeMsg($code);
                $data = null;
            }

        }while(false);
        return compact('code', 'msg', 'data');
    }

    public function addDynamic($img,$url,$name){
        return $this->model_room->addDynamic($img,$url,$name);
    }

    public function updateDynamic($id,$img,$url,$name){
        return $this->model_room->updateDynamic($id,$img,$url,$name);
    }

    public function delDynamic($id){
        return $this->model_room->delDynamic($id);

    }


    /********************** 房间功能开关设置********************/
    /**
     * 获取房间功能开关状态，默认开启
     * @param $roomId
     * @param $switch_key
     * @return int
     */
    public function getRoomSwitchCommon($roomId, $switch_key)
    {
        $info = $this->model_room -> getRoomBySwitch($roomId, $switch_key);
        $state = 1;
        if ($info){
            $state = isset($info['switch_value']) ? $info['switch_value'] : 0;
        }
        return (int) $state;
    }

    /**
     * 设置房间功能开关
     * @param $roomId
     * @param $switch_key
     * @param $switch_value
     * @return bool|int
     */
    public function setRoomSwitchCommon($roomId, $switch_key, $switch_value)
    {
        $roomId = (int) $roomId;
        $switch_key = (string) $switch_key;
        $switch_value   = (int) $switch_value;
        $info = $this->model_room -> getRoomBySwitch($roomId, $switch_key);
        if ($info){
            $state = $this->model_room -> setRoomBySwitch($roomId, $switch_key, $switch_value);
        }else{
            $state = $this->model_room -> addRoomBySwitch($roomId, $switch_key, $switch_value);
        }
        if ($state){
            // send msg
            (new RoomMsgServices())->sendRoomSwitchMsg($roomId, $switch_key, $switch_value);
        }
        return $state;
    }

    public function setUserInRoomTime(int $roomId, int $userId, int $second) {

        return true;
    }

    /**
     * 一起玩房间列表
     */
    public function gameRoomList($page, $page_size, $room_mode=0) {
        $list = $this->model_room->getAllRoomOpenList();
        $roomList = [];
        foreach($list as $key=>$val) {
            [$roomId, $type] = explode(':', $key);
            if($type == 'roomMode') {
                if(in_array($val, [2, 3, 4])) {
                    if(!empty($room_mode)) {
                        if($room_mode==$val) {
                            $roomList[$roomId] = [
                                'roomId' => $roomId,
                                'roomUserNum' => $list[$roomId.':roomUserNum'],
                            ];
                        }
                    }else{
                        $roomList[$roomId] = [
                            'roomId' => $roomId,
                            'roomUserNum' => $list[$roomId.':roomUserNum'],
                        ];
                    }
                }
            }
        }
        array_multisort(array_column($roomList, 'roomUserNum'), SORT_DESC, $roomList);
        //分页
        $roomList = array_slice($roomList, $page*$page_size, $page_size);
        $roomIds = array_column($roomList, 'roomId');
        $roomInfoList = $this->model_room->get_rooms_by_ids($roomIds);
        $roomInfoList = array_column($roomInfoList, null, 'room_id');

        $data = [];
        foreach($roomList as $val) {
            if(empty($roomInfoList[$val['roomId']])) {
                continue;
            }
            $roomInfo = $roomInfoList[$val['roomId']];
            $roomInfo['roomUserNum'] = $val['roomUserNum'];
            $data[] = $roomInfo;
        }

        return ['list'=>$data];
    }

    /**
     * 获取可加入的游戏房间
     */
    public function getCanPlayGameRoom($room_mode=0) {
        $list = $this->model_room->getAllRoomOpenList();
        $roomIds = [];
        foreach($list as $key=>$val) {
            [$roomId, $type] = explode(':', $key);
            if($type == 'roomMode') {
                if(!empty($room_mode) && $room_mode==$val) {
                    $roomIds[] = $roomId;
                }
            }
        }
        $roomId = 0;
        if(!empty($roomIds)) {
            $roomId = (int) $roomIds[array_rand($roomIds)];
        }

        return ['room_id' => $roomId];
    }
    /**
     * 添加修改特殊封面
     * @param $roomid 房间id
     * @param $imgurl 封面图
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     * @return bool
     */
    public function specialRoomCreateOrUp($roomid=0,$imgurl='',$start_time,$end_time)
    {
        $data['roomid'] = $roomid; //房间id
        $data['special_img'] = $imgurl; //房间特殊封面
        $data['start_time'] = $start_time; //开始时间
        $data['end_time'] = $end_time; //结束时间
        $data['create_time'] = date('Y-m-d H:i:s',time());//创建时间
        $status = $this->model_room->InsertOrUpSpecailImg($data);
        return $status;
    }

    /**
     * 删除房间特殊封面
     */
    public function specialRoomDel($roomid=0)
    {
        $status = $this->model_room->delSpecailImg($roomid);
        return $status;
    }

    //未充值用户弹出首充弹出
    public function showFirstPop($user_id){
        // //获取用户充值记录
        // $rechargeCount = $this->finance_recharge_order_model->getPayNumByUserId($user_id);
        // $msg['pop_type'] = 0;
        // if($rechargeCount == 0){
        //     //返回弹出首充弹窗
        //     $msg['pop_type'] = 1;//0=用户未充值 1=用户未充值首充弹窗
        // }
        $msg = [];
        $msg['pop_type'] = 0;
        return $msg;
    }

    /**
     * 获取用户首次充值
     */
    public function isFirstUser($userid)
    {
        //获取用户充值单数
        $statusInfo = $this->finance_recharge_order_model->isFristRecharge($userid);
        $msg = [];
        if(empty($statusInfo['count']) || empty($statusInfo['orderinfo']))
        {
            return $msg;
        }
        //充值单数等于1并且充值金额大于600(6元),并且没有领取券的显示弹窗
        $getLuckTicke = $this->luck_draw_user_prop_model->getAvail(1000,$userid);//普通池抽奖券
        $price = 600;//充值金额大于600(6元)
        if($statusInfo['count'] ==1 && $statusInfo['orderinfo']['price'] >=$price && $getLuckTicke==0)
        {
            //返回客户端弹窗信息
            $msg['title'] = '恭喜您解锁'.PHP_EOL.'首次充值福利';
            $msg['confirm_content'] = '获得许愿转盘免费体验劵*1';
            $msg['error_content'] = '确放弃免费体验劵*1吗?';
            //获取今日弹窗数若今日弹窗一次则下次不弹出
            $todayPopCount = Redis::get($this->firstRecharge_key.$userid);
            if(!empty($todayPopCount)){
                $msg = [];
            }else{
                Redis::set($this->firstRecharge_key.$userid,1);
                Redis::expire($this->firstRecharge_key.$userid,86400);
            }
        }
        return $msg;
    }
    /**
     * 设备检测是否领取过券
     */
    public function getIssetTicketLog($guid)
    {
        return $this->finance_recharge_order_model->getIssetTicketLog($guid);
    }
    /**
     * 新用户发放许愿池券
     */
    public function getLuckTicket($userid,$guid)
    {
        //获取用户充值单数
        $statusInfo = $this->finance_recharge_order_model->isFristRecharge($userid);
        $data = [];
        if(empty($statusInfo['count']) || empty($statusInfo['orderinfo']))
        {
            return $data;
        }
        //充值单数等于1并且充值金额大于600(6元),并且没有领取券的发放券
        $getLuckTicke = $this->luck_draw_user_prop_model->getAvail(1000,$userid);//普通池抽奖券
        $price = 600;//充值金额大于600(6元)
        if($statusInfo['count'] ==1 && $statusInfo['orderinfo']['price'] >=$price && $getLuckTicke==0)
        {
            //发放许愿池抽奖券普通池*1
            $res = $this->luck_draw_user_prop_model->add(1000,$userid,1);
            if($res)
            {
                //更新log
                $this->finance_recharge_order_model->updateFirstTicketLog($userid,$guid);
                $data['action_url'] = 'kkaudio://luckyWheel';
            }
        }
        return $data;
    }

}
